/**
 * Created by Administrator on 2017/2/9.
 */

var roomManager = require('../../../logic/world/roomManager');
var SMS = require('../../../SDK/SMS').AliyunSmsUtil;
var systemConfig = require('../../../../config/systemConfig');
var defaultGlobal = require('../../../../config/defaultGlobal.json');
module.exports = function (app) {
    return new Handler(app);
};

var Handler = function (app) {
    this.app = app;
};

var handler = Handler.prototype;

handler.setInviter = function (msg, session, next) {
    var self = this;
    var uid = session.uid;
    if (isNaN(msg.inviter) || !msg.inviter) {
        next(null, {code: Code.ARGS_INVALID});
        return;
    }

    var inviterUid = parseInt(msg.inviter);
    if (uid == inviterUid) {
        next(null, {code: Code.UID_IS_SELF});
        return;
    }

    var resp = {};
    async.waterfall([
        function (cb) {
            gPlayerManger.getPlayer(uid, function (p) {
                cb((p) ? null : Code.DB_ERROR, p);
            });
        }, function (player, cb) {
            gPlayerManger.getPlayer(inviterUid, function (p) {
                cb((p) ? null : Code.UID_INVALID, player, p);
            });
        }, function (player, inviter, cb) {
            var user = player.user;

            if (user.invite.inviter) {
                cb(Code.INVITER_SETTED);
                return;
            }
            if (defaultGlobal.InviterIsAgency) {
                if (!inviter.isAgency()) {
                    cb(Code.NOT_AGENCY);
                    return;
                }
            }
            logger.debug("player level %d inviter level %d", player.user.gm.level, inviter.user.gm.level);
            if (inviter.user.gm.level == 0) {
                cb(Code.AGENCY_LEVEL_LOW);
                return;
            } else if (inviter.user.gm.level > 0) {
                if (player.user.gm.level == 0) {
                    if (inviter.user.gm.level == Def.GM_LEVEL_SUPER) {
                        cb(Code.AGENCY_LEVEL_LOW);
                        return;
                    }
                } else {
                    if (player.user.gm.level <= inviter.user.gm.level || inviter.user.gm.level == Def.GM_LEVEL_SUPER) {
                        cb(Code.AGENCY_LEVEL_LOW);
                        return;
                    }
                }
            }


            user.invite.inviter = inviterUid;
            user.invite.inviteTime = Date.getStamp();
            player.markDirty("invite");
            resp.inviter = inviterUid;

            // var config = gGlobalManager.getConfig("inviteSetting");
            // if (config) {
            //     if (config.inviterResource) {
            //         inviter.addResource(config.inviterResource, "inviter");
            //     }
            //     if (config.userResource) {
            //         player.addResource(config.userResource, "setInviter");
            //         resp.reward = config.userResource;
            //     }
            // }
            player.save();
            cb();
        }
    ], function (err) {
        if (err) {
            next(err, {code: err});
            return;
        }

        next(null, resp);
    });
};

handler.getInviter = function (msg, session, next) {
    var self = this;
    var inviterUid = parseInt(session.uid);

    async.series([
        function (cb) {
            gPlayerManger.getPlayer(inviterUid, function (p) {
                cb((p) ? null : Code.UID_INVALID, p);
            });
        }, function (cb) {
            gPlayerManger.getInviter(inviterUid, function (err, list) {
                if (err) {
                    cb(err);
                }
                var resp = {};
                resp.arr = [];
                if (list.length > 0) {
                    for (var i = 0; i < list.length; i++) {
                        var temp = {};
                        temp.headpic = list[i].info.headpic;
                        temp.name = list[i].info.name;
                        resp.arr.push(temp);
                    }
                }
                cb(null, resp);
            });
        }
    ], function (err, resp) {
        if (err) {
            next(err, {code: err});
            return;
        }
        next(null, resp[1]);
    });
};

handler.exchangeCoin = function (msg, session, next) {
    var self = this;
    var uid = session.uid;

    if (isNaN(msg.num) || !msg.resource) {
        next(null, {code: Code.ARGS_INVALID});
        return;
    }


    var resourceName = msg.resource || 'card';
    var num = parseInt(msg.num);
    var exchangeRate = 0;
    if (msg.key) {
        exchangeRate = gGlobalManager.getConfig("exchange", resourceName + "ToCoin" + msg.key) || 0;
    } else {
        exchangeRate = gGlobalManager.getConfig("exchange", resourceName + "ToCoin") || 0;
    }
    if (!exchangeRate) {
        next(null, {code: Code.EXCHANGE_NOT_OPEN});
        return;
    }

    var player = null;
    async.series([
        function (cb) {
            gPlayerManger.getPlayer(uid, function (p) {
                player = p;
                if (!player) {
                    cb(Code.DB_ERROR);
                    return;
                }

                if (!player.checkResource(resourceName, num)) {
                    cb(Code.LACK_OF_RESOURCE);
                    return;
                }

                var resource = {};
                resource[resourceName] = -num;
                resource['coin'] = Math.floor(num * exchangeRate);

                player.alterResource(resource, "exchangeCoin");
                cb();
            });
        }
    ], function (err) {
        if (err) {
            next(err, {code: err});
            return;
        }

        next(null, {"status": player.user.status});
    });
};

handler.fetchShareReward = function (msg, session, next) {
    var uid = session.uid;
    var player = null;
    var resp = {};

    async.series([
        function (cb) {
            gPlayerManger.getPlayer(uid, function (p) {
                player = p;
                if (!player) {
                    cb(Code.DB_ERROR);
                    return;
                }

                if (player.getDayVar("shareReward")) {
                    cb(Code.REWARD_FETCHED);
                    return;
                }
                cb();
            });
        }, function (cb) {
            var resource = gGlobalManager.getConfig("shareReward");
            if (!resource) {
                cb(Code.ACTIVITY_NOT_OPEN);
                return;
            }

            player.addDayVar('shareReward', 1);
            player.addResource(resource, "shareReward");

            var rewardEx = gGlobalManager.getConfig("sharedRewardEx", "bigWheel");
            console.log("幸运大转盘次数:" + rewardEx);
            if (rewardEx) {
                player.addDayVar("bigWheelTimes", rewardEx);
            }

            resp.resource = resource;
            cb();
        },
    ], function (err) {
        if (err) {
            next(err, {code: err});
            return;
        }

        next(null, resp);
    });
};
handler.SevenDayReward = function (msg, session, next) {
    this.sevenDayReward(msg, session, next);
};

handler.sevenDayReward = function (msg, session, next) {
    var uid = session.uid;
    var player = null;
    var resp = {};

    async.series([
        function (cb) {
            gPlayerManger.getPlayer(uid, function (p) {
                player = p;
                if (!player) {
                    cb(Code.DB_ERROR);
                    return;
                }

                if (player.getDayVar("SevenDayReward")) {
                    cb(Code.REWARD_FETCHED);
                    return;
                }
                var now = new Date();
                var dayPassed = now.getDayPassed(player.user.info.createTime);

                if (dayPassed > 7) {
                    cb(Code.REWARD_FETCHED);
                    return;
                }
                cb();
            });
        }, function (cb) {
            var resource = gGlobalManager.getConfig("SevenDayReward");
            if (!resource) {
                cb(Code.ACTIVITY_NOT_OPEN);
                return;
            }

            player.addDayVar('SevenDayReward', 1);

            player.markDirty("activitySign");

            player.addResource(resource, "SevenDayReward");
            resp.resource = resource;

            cb();
        },
    ], function (err) {
        if (err) {
            next(err, {code: err});
            return;
        }

        next(null, resp);
    });
};
handler.SignDayReward = function (msg, session, next) {
    this.signDayReward(msg, session, next);
};
handler.signDayReward = function (msg, session, next) {
    var uid = session.uid;
    var player = null;
    var resp = {};

    async.series([
        function (cb) {
            gPlayerManger.getPlayer(uid, function (p) {
                player = p;
                if (!player) {
                    cb(Code.DB_ERROR);
                    return;
                }
                if (player.getDayVar("SignReward")) {
                    cb(Code.REWARD_FETCHED);
                    return;
                }
                cb();
            });
        }, function (cb) {
            var config = gGlobalManager.getConfig("SignReward");
            if (!config) {
                cb(Code.ACTIVITY_NOT_OPEN);
                return;
            }

            player.addDayVar('SignReward', 1);
            var act = player.getactivitySign();
            if (!act) {
                act = player.addactivitySign();
            }
            var now = player.getDayVar('day');
            if (now - act.lastTime == 1) {
                act.seriesDays += 1;
                if (act.seriesDays == 6) {
                    act.seriesDays = 1;
                }
            } else {
                act.seriesDays = 1;
            }

            var time = new Date();
            var lastTime = new Date();
            var nowTime = (act.lastTime * 86400000) + (time.getTimezoneOffset() * 60000);
            lastTime.setTime(nowTime);
            var lastMonth = lastTime.getMonth();
            var today = time.getDate();
            var month = time.getMonth();
            //console.log("month = %d  l++++++++++lastMonth = %d", month, lastMonth);
            if (today == 1 || month != lastMonth) {
                act.monthCount = 1;
                act.signs = [];
            }
            if (!act.hasOwnProperty("signs")) {
                act.signs = [];
            }
            act.monthCount += 1;
            act.signs.push(today);
            act.lastTime = now;

            var reward = {};
            if (config.total) {
                var curTotalReward = config.total[act.monthCount];
                if (curTotalReward) {
                    ExObject.merge(reward, curTotalReward);
                }
            }
            if (config.series) {
                var curSeriesReward = config.series[act.seriesDays];
                if (curSeriesReward) {
                    ExObject.merge(reward, curSeriesReward);
                }
            }
            player.markDirty("activitySign");
            player.addResource(reward, "SignReward");
            resp.resource = reward;
            cb();
        },
    ], function (err) {
        if (err) {
            next(err, {code: err});
            return;
        }

        next(null, resp);
    });
};
handler.JoinClub = function (msg, session, next) {
    this.joinClub(msg, session, next);
};
handler.joinClub = function (msg, session, next) {
    var uid = session.uid;

    if (isNaN(msg.clubId)) {
        next(null, {code: Code.ARGS_INVALID});
        return;
    }

    var clubId = parseInt(msg.clubId);
    var clubOwner = null;
    var player = null;

    async.series([
        function (cb) {
            gPlayerManger.getPlayer(clubId, function (p) {
                if (!p) {
                    cb(Code.UID_INVALID);
                    return;
                }

                clubOwner = p;
                if (!clubOwner.getGmLevel()) {
                    cb(Code.GM_NOT_AGENT);
                    return;
                }

                cb();
            });
        },
        function (cb) {
            gPlayerManger.getPlayer(uid, function (p) {
                if (!p) {
                    cb(Code.DB_ERROR);
                    return;
                }

                player = p;
                if (player.user.Club) {
                    cb(Code.JOIN_CLUB_FAILED);
                    return;
                }

                player.user.Club = clubId;
                player.markDirty("Club");

                var resource = gGlobalManager.getConfig("ClubJoinReward");
                if (resource) {
                    player.addResource(resource, "ClubJoinReward");
                }

                player.save(true);
                cb();
            });
        }
    ], function (err) {
        if (err) {
            next(err, {code: err});
            return;
        }

        next(null, {"Club": player.user.Club});
    });
};
handler.GetSignDay = function (msg, session, next) {
    this.getSignDay(msg, session, next);
}
handler.getSignDay = function (msg, session, next) {
    var uid = session.uid;
    var player = null;
    var resp = {};

    async.series([
        function (cb) {
            gPlayerManger.getPlayer(uid, function (p) {
                player = p;
                if (!player) {
                    cb(Code.DB_ERROR);
                    return;
                }

                cb();
            });
        }, function (cb) {
            var reward = {};
            var act = player.getactivitySign();
            if (!act) {
                act = player.addactivitySign();
            }
            var time = new Date();
            var lastTime = new Date();
            var nowTime = (act.lastTime * 86400000) + (time.getTimezoneOffset() * 60000);
            lastTime.setTime(nowTime);
            var lastMonth = lastTime.getMonth();
            var today = time.getDate();
            var month = time.getMonth();
            if (today == 1 || month != lastMonth) {
                act.monthCount = 1;
                act.signs = [];
            }
            if (!act.hasOwnProperty("signs")) {
                act.signs = [];
            }
            reward.seriesDays = act.seriesDays;
            reward.lastTime = act.lastTime;
            reward.monthCount = act.monthCount;
            reward.signs = act.signs;
            reward.totalReward = gGlobalManager.getConfig("SignReward", "total");
            var now = player.getDayVar('day');
            if (now - act.lastTime == 1) {

            } else {
                reward.seriesDays = 0;
            }
            resp.SignDays = reward;
            cb();
        },
    ], function (err) {
        if (err) {
            next(err, {code: err});
            return;
        }

        next(null, resp);
    });
};

handler.activityTotalPlayReward = function (msg, session, next) {
    msg.key = "totalPlay";
    this.fetchActivityReward(msg, session, next);
};

handler.fetchActivityReward = function (msg, session, next) {
    var uid = session.uid;
    var key = msg.key;

    var resp = {};
    async.series([
        function (cb) {
            gPlayerManger.getPlayer(uid, function (player) {
                if (!player) {
                    cb(Code.DB_ERROR);
                    return;
                }

                var activityConf = gGlobalManager.getConfig('Activity', key);
                if (!activityConf) {
                    cb(Code.ACTIVITY_NOT_OPEN);
                    return;
                }

                var activityInfo = player.getActivity(key);
                if (!activityInfo) {
                    cb(Code.ACTIVITY_NOT_REACH);
                    return;
                }

                if (activityInfo.level >= activityConf.conditions.length) {
                    cb(Code.ACTIVITY_FETCHED);
                    return;
                }
                var condition = activityConf.conditions[activityInfo.level];
                if (!condition) {
                    cb(Code.ACTIVITY_FETCHED);
                    return;
                }

                if (activityInfo.value < condition.value) {
                    cb(Code.ACTIVITY_NOT_REACH);
                    return;
                }

                activityInfo.level += 1;
                player.markDirty("activity");

                var reward = condition.reward;
                player.addResource(reward, "Activity_" + key);
                resp.resource = reward;
                cb();
            });
        }
    ], function (err) {
        if (err) {
            resp.code = err;
        }

        next(null, resp);
    });
};

handler.fetchDailyActivityReward = function (msg, session, next) {
    var uid = session.uid;
    var key = msg.key;

    var resp = {};
    async.series([
        function (cb) {
            gPlayerManger.getPlayer(uid, function (player) {
                if (!player) {
                    cb(Code.DB_ERROR);
                    return;
                }

                var activityConf = gGlobalManager.getConfig('DailyActivity', key);
                if (!activityConf) {
                    cb(Code.ACTIVITY_NOT_OPEN);
                    return;
                }

                var activityInfo = player.user.dailyActivity[key];
                if (!activityInfo) {
                    cb(Code.ACTIVITY_NOT_REACH);
                    return;
                }

                if (activityInfo.level >= activityConf.conditions.length) {
                    cb(Code.ACTIVITY_FETCHED);
                    return;
                }
                var condition = activityConf.conditions[activityInfo.level];
                if (!condition) {
                    cb(Code.ACTIVITY_FETCHED);
                    return;
                }

                if (activityInfo.value < condition.value) {
                    cb(Code.ACTIVITY_NOT_REACH);
                    return;
                }

                activityInfo.level += 1;
                player.markDirty("dailyActivity");

                var reward = condition.reward;
                player.addResource(reward, "DailyActivity_" + key);
                resp.resource = reward;
                cb();
            });
        }
    ], function (err) {
        if (err) {
            resp.code = err;
        }

        next(null, resp);
    });
};
handler.authentication = function (msg, session, next) {
    var uid = session.uid;
    var player = null;
    var resp = {};

    console.log(JSON.stringify(msg));

    async.series([
        function (cb) {
            gPlayerManger.getPlayer(uid, function (p) {
                player = p;
                if (!player) {
                    cb(Code.DB_ERROR);
                    return;
                }

                if (player.user.authenticationInfo) {
                    cb(Code.AUTHENTICATION_END);
                    return;
                }

                if (!msg.name || !msg.id) {
                    cb(Code.AUTHENTICATION_FAILED);
                    return;
                }
                cb();
            });
        }, function (cb) {

            // 处理检测验证码
            if (gGlobalManager.getConfig("AuthenticationCheckSign", "needCheckSign")) {

                // 获取玩家的验证码 进行检验
                var data = gCheckSignManager.getCheckData(uid);

                if (!data || !data.sign || !msg.Ver) {
                    cb(Code.NEED_SIGN);
                    return;
                }

                if (!msg.phone || msg.phone != data.phone) {
                    cb(Code.NOT_MATCHED_PHONENUM);
                    return;
                }

                if (data.sign != msg.Ver) {
                    cb(Code.WRONG_SIGN);
                    return;
                }
            }

            cb();
        }
    ], function (err) {
        if (err) {
            next(err, {code: err});
            return;
        }

        if (!player.user.authenticationInfo) {
            player.user.authenticationInfo = {
                name: 0,
                phone: 0,
                id: 0
            };
        }

        // 关键字存储
        player.user.authenticationInfo.name = msg.name;
        player.user.authenticationInfo.id = msg.id;
        if (msg.phone) {
            player.user.authenticationInfo.phone = msg.phone;
        }

        player.markDirty("authenticationInfo");

        var reward = gGlobalManager.getConfig('AuthenticationReward');
        if (reward) {
            player.addResource(reward, "AuthenticationReward");
        }
        resp.resource = reward;

        next(null, resp);
    });
};

/**
 * 获取玩家的验证码
 * @param msg
 * @param session
 * @param next
 */
handler.getCheckSign = function (msg, session, next) {

    // 如果没有开启需要验证码，则不能往下执行
    if (!gGlobalManager.getConfig("AuthenticationCheckSign", "needCheckSign")) {
        next(null, {code: Code.SYSTEM_ERROR});
        return;
    }

    // 获取玩家的uid
    var uid = session.uid;
    var gameType = msg.gameType;

    var useConfig = gCheckSignManager.getConfig("SMS", gameType);

    if (useConfig == null) {
        console.log("没有对应的配置");
        next(null, {code: Code.DB_ERROR});
        return;
    }

    gPlayerManger.getPlayer(uid, function (p) {

        var player = p;

        if (!player) {
            console.log("玩家不存在");
            next(null, {code: Code.DB_ERROR});
            return;
        }

        // 获取到玩家的数据
        // 并验证是否已经超过获取时长
        // 如果已经超过则返回为空
        var data = gCheckSignManager.getCheckData(uid);

        var isOverTime = true;

        if (data && data.time) {

            // 查看当前的时间是否已经过了
            var overTime = useConfig.EffectTime;
            var curTime = Date.getStamp();

            if (curTime - data.time < overTime) {
                next(null, {code: Code.ARGS_INVALID});
                return;
            }
        }

        // 判断玩家当前的验证码时长是否已经超过获取时长
        if (isOverTime) {

            data = gCheckSignManager.addCheckSign(uid, msg.phone, useConfig);

            SMS.sendMessage(useConfig, data, function (err, response, data) {

                if (err) {
                    console.log("发送错误：" + err);
                    next(err, {code: Code.DB_ERROR});
                    return;
                }

                next(null, {code: Code.SUCCESS});
            }.bind(this));
        }
    }.bind(this));

};

handler.getResourceByBox = function (msg, session, next) {
    var uid = session.uid;
    var player = null;
    var resp = {};
    var resource = {};
    async.series([
        function (cb) {
            gPlayerManger.getPlayer(uid, function (p) {
                player = p;
                if (!player) {
                    cb(Code.DB_ERROR);
                    return;
                }
                if (!msg) {
                    cb(Code.ARGS_INVALID);
                    return;
                }
                var boxResource = gGlobalManager.getConfig("storageBoxInitResource");
                if (!player.user.storageBox) {
                    player.user.storageBox = boxResource;
                }
                var flag = false;
                ExObject.each(boxResource, function (k, v) {
                    if (msg.hasOwnProperty(k)) {
                        resource[k] = msg[k];
                        flag = true
                    }
                });
                if (!flag) {
                    cb(Code.ARGS_INVALID);
                    return;
                }
                cb();
            });
        }, function (cb) {
            var flag = true;
            ExObject.each(resource, function (k, v) {
                if (player.user.storageBox[k] < v) {
                    flag = false;
                    return true;
                }
            });
            if (!flag) {
                cb(Code.LACK_OF_STORAGE_COIN);
                return;
            }
            cb();

        }, function (cb) {
            ExObject.each(resource, function (k, v) {
                player.user.storageBox[k] -= v;
            });
            player.addResource(resource, "getResourceByBox");
            resp.storageBox = player.user.storageBox;
            resp.status = player.getResource();

            player.markDirty("storageBox");

            cb();
        },
    ], function (err) {
        if (err) {
            next(err, {code: err});
            return;
        }
        next(null, resp);
    });
};
handler.giveResourceToBox = function (msg, session, next) {
    var uid = session.uid;
    var player = null;
    var resp = {};
    var resource = {};
    async.series([
        function (cb) {
            gPlayerManger.getPlayer(uid, function (p) {
                player = p;
                if (!player) {
                    cb(Code.DB_ERROR);
                    return;
                }
                if (!msg) {
                    cb(Code.ARGS_INVALID);
                    return;
                }
                var boxResource = gGlobalManager.getConfig("storageBoxInitResource");
                if (!player.user.storageBox) {
                    player.user.storageBox = boxResource;
                }
                var flag = false;
                ExObject.each(boxResource, function (k, v) {
                    if (msg.hasOwnProperty(k)) {
                        resource[k] = msg[k];
                        flag = true
                    }
                });
                if (!flag) {
                    cb(Code.ARGS_INVALID);
                    return;
                }
                cb();
            });
        }, function (cb) {
            var flag = true;
            ExObject.each(resource, function (k, v) {
                if (player.user.status[k] < v) {
                    flag = false;
                    return true;
                }
            });
            if (!flag) {
                cb(Code.LACK_OF_COIN);
                return;
            }
            cb();

        }, function (cb) {
            logger.debug("resource = %j", resource);
            ExObject.each(resource, function (k, v) {
                player.user.storageBox[k] += v;
            });
            player.costResource(resource, "giveResourceToBox");
            resp.storageBox = player.user.storageBox;
            resp.status = player.getResource();

            player.markDirty("storageBox");

            cb();
        },
    ], function (err) {
        if (err) {
            next(err, {code: err});
            return;
        }
        next(null, resp);
    });
};
handler.exchangeFixedCoin = function (msg, session, next) {
    var uid = session.uid;
    var resp = {};
    var mod = msg.exchangeMod;
    var exchangeInfo = {};
    exchangeInfo = gGlobalManager.getConfig("fixedExchange", mod) || 0;
    if (!exchangeInfo) {
        next(null, {code: Code.EXCHANGE_NOT_OPEN});
        return;
    }
    var player = null;
    async.series([
        function (cb) {
            gPlayerManger.getPlayer(uid, function (p) {
                player = p;
                if (!player) {
                    cb(Code.DB_ERROR);
                    return;
                }
                var cost = exchangeInfo.give;
                if (!player.checkResource(cost)) {
                    cb(Code.LACK_OF_RESOURCE);
                    return;
                }
                var add = exchangeInfo.get;
                player.costResource(cost, "exchangeCoin");
                player.addResource(add, "exchangeCoin");
                resp = player.user.status;
                cb();
            });
        }
    ], function (err) {
        if (err) {
            next(err, {code: err});
            return;
        }

        next(null, resp);
    });
};

// 获取大转盘的配置内容
handler.getBigWheelConfig = function (msg, session, next) {

    var bigWheelConfig = gGlobalManager.getConfig("BigWheel");

    next(null, bigWheelConfig);
};

// 获取大转盘的奖励
handler.getWheelReward = function (msg, session, next) {

    // 获取当前玩家状态
    var player = null;
    var uid = session.uid;

    gPlayerManger.getPlayer(uid, function (p) {

        player = p;

        if (!player) {
            next(null, {code: Code.DB_ERROR});
            return;
        }

        // 判断当前是否已经进行了分享
        if (!player.getDayVar("shareReward")
            && !player.getDayVar("bigWheelTimes")) {
            next(null, {code: 8001});
            return;
        }

        // 判断当前是否已经领取了奖励
        if (!player.getDayVar("bigWheelTimes")) {
            next(null, {code: 8002});
            return;
        }

        // 获取总的权重
        var bigWheel = gGlobalManager.getConfig("BigWheel");
        var sumWeight = 0;

        for (var index in bigWheel) {

            var weight = parseInt(bigWheel[index].weight);

            if (weight) {
                sumWeight += weight;
            }
        }

        // 进行random 获取转盘值
        var randomNum = Ext.randRange(0, sumWeight);
        var rateBase = 0;
        var rewardIndex = 0;
        for (var index in bigWheel) {

            var weight = parseInt(bigWheel[index].weight);

            if (weight) {
                var curRate = rateBase + weight;

                if (randomNum >= rateBase && randomNum < curRate) {
                    rewardIndex = index;
                    break;
                }

                rateBase = curRate;
            }
        }

        // 配置有误
        if (rewardIndex == 0) {
            next(null, {code: 8003});
            return;
        }

        // 发送奖励
        var rewardInfo = gGlobalManager.getConfig("BigWheel", rewardIndex);
        player.alterResource(rewardInfo["resource"], "幸运大转盘");

        // 将当前玩家的次数进行减一
        player.addDayVar("bigWheelTimes", -1);

        next(null, {index: rewardIndex});
    }.bind(this));

};
//苹果
handler.IOSInAppPurchase = function (msg, session, next) {
    var iap = require('iap');
    var platform = 'apple';
    var uid = session.uid;
    var payment = {
        receipt: msg.receipt, // always required
        productId: msg.productId,
        packageName: systemConfig.IAP.packageName,
        secret: 'password',
        subscription: false,	// optional, if google play subscription
        //devToken: 'developer id' // required, if roku
    };
    gPlayerManger.getPlayer(uid, function (player) {
        if (!player) {
            next(null,{code: Code.DB_ERROR});
            return;
        }
        iap.verifyPayment(platform, payment, function (error, response) {
            /* your code */
            logger.debug("err = %j, resp = %j", error, response);
            if(!error) {
                if (msg.productId == response.productId) {
                    if (msg.transactionIdentifier == response.transactionId) {
                        var findCondition = {
                            "_id": 'qzmj' + response.transactionId
                        };
                        async.waterfall([
                            function (cb) {
                                DB.onlinepay.findOne(findCondition, function (err, result) {
                                    if (err) {
                                        cb(err);
                                        return
                                    }
                                    if (!result) {
                                        var reward = systemConfig.IAP.rewards[response.productId];
                                        player.addResource(reward, "IOSInApp");
                                        var time = Date.parse(new Date());
                                        var sets = {
                                            "_id": findCondition._id,
                                            "platform": "ioszf",
                                            "status": 1,
                                            "bank": "",
                                            "uid": uid,
                                            "money": 0,
                                            "item": 0,
                                            "time": time,
                                            "refer": 0
                                        };
                                        DB.onlinepay.save(sets, function (err) {
                                            //console.log("save errr");
                                        });
                                        next(null, {code: 0});
                                    } else {
                                        next(null, {code: Code.IAP_TRANSACTIONID_EXITS});
                                    }
                                });
                            }
                        ], function (err) {
                            logger.debug("DB err");
                        });
                    } else {
                        next(null, {code: Code.IAP_TRANSACTIONID_ERROR});
                    }
                } else {
                    next(null, {code: Code.IAP_PRODUCTID_ERROR});
                }
            }else {
                next(null, {code: Code.IAP_ERROR, err: error});
            }
        });
    });
};
